#!/usr/bin/python

# Ubuntu Tweak - Ubuntu Configuration Tool
#
# Copyright (C) 2007-2011 Tualatrix Chou <tualatrix@gmail.com>
#
# Ubuntu Tweak is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Ubuntu Tweak is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ubuntu Tweak; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA

import os
import sys
import optparse
import logging

import dbus
import dbus.service
import dbus.mainloop.glib

from gi.repository import GObject, Gdk, Gtk, Gio

Gdk.threads_init()
GObject.threads_init()
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
dbus.mainloop.glib.threads_init()

from ubuntutweak import system
from ubuntutweak.common.consts import VERSION, IS_INSTALLED, IS_TESTING, DATA_DIR
from ubuntutweak.common.debug import enable_debugging


def show_splash():
    win = Gtk.Window(type=Gtk.WindowType.POPUP)
    win.set_position(Gtk.WindowPosition.CENTER)

    vbox = Gtk.VBox()
    image = Gtk.Image()
    image.set_from_file(os.path.join(DATA_DIR, 'pixmaps/splash.png'))

    vbox.pack_start(image, True, True, 0)
    win.add(vbox)

    win.show_all()

    while Gtk.events_pending():
        Gtk.main_iteration()

    return win

def parse_args(argv):
    parser = optparse.OptionParser(prog="ubuntu-tweak",
                                   version="%%prog %s" % VERSION,
                                   description="Ubuntu Tweak is a tool for Ubuntu that makes it easy to configure your system and desktop settings.")
    parser.add_option("-d", "--debug", action="store_true", default=False,
                      help="Generate more debugging information.  [default: %default]")
    parser.add_option("-m", "--module", dest="module", default='',
                      help="Start module directly.  [default: %default]")
    parser.add_option("-f", "--feature", dest="feature", default='',
                      help="Start feature directly.  [default: %default]")
    return parser.parse_args(argv)


class UbuntuTweakApp(Gtk.Application):
    _window = None
    log = logging.getLogger('Launcher')

    def __init__(self, application_id='com.ubuntu-tweak.Tweak'):
        Gtk.Application.__init__(self,
                                 application_id=application_id,
                                 flags=Gio.ApplicationFlags.HANDLES_COMMAND_LINE)

        self.log.debug("Distribution: %s\nApplication: %s\nDesktop:%s" % (system.DISTRO,
                                           system.APP,
                                           system.DESKTOP))

        self.connect('activate', self.on_activated)
        self.connect('startup', self.on_startup)
        self.connect('command-line', self.on_command_line)

    def on_startup(self, app):
        splash_window = show_splash()
        from ubuntutweak.main import UbuntuTweakWindow

        self._window = UbuntuTweakWindow(feature=options.feature, module=options.module, splash_window=splash_window)
        self.add_window(self._window.mainwindow)

        Gtk.main()

    def on_activated(self, app):
        if self.get_windows():
            self.get_windows()[0].present()

    def on_command_line(self, app, commandline):
        self.log.debug("on_command_line: %s", commandline.get_arguments())

        options, args = parse_args(commandline.get_arguments())

        self.on_activated(app)

        if options.feature:
            self._window.select_target_feature(options.feature)

        if options.module:
            self._window.do_load_module(options.module)

if __name__ == "__main__":
    options, args = parse_args(sys.argv)

    if options.debug or not IS_INSTALLED or IS_TESTING:
        enable_debugging()

    app = UbuntuTweakApp()
    app.run(sys.argv)
